// Stopwatch
var stopwatchInterval = 0;      // The interval for our loop.
var count = 0; //次数

var stopwatchClock = $(".simple.stopwatch").find(".clock"),
    stopwatchDigits = stopwatchClock.find('span');

var singleIds = [];
$.getJSON(getRootPath()+"user/getAllUserIdCombo.do",function(result){
	singleIds = result;
});

// Checks if the previous session was ended while the stopwatch was running.
// If so start it again with according time.
if(Number(localStorage.stopwatchBeginingTimestamp) && Number(localStorage.stopwatchRunningTime)){

    var runningTime = Number(localStorage.stopwatchRunningTime) + new Date().getTime() - Number(localStorage.stopwatchBeginingTimestamp);

    localStorage.stopwatchRunningTime = runningTime;

    startStopwatch();
}

// If there is any running time form previous session, write it on the clock.
// If there isn't initialise to 0.
if(localStorage.stopwatchRunningTime){
    stopwatchDigits.text(returnFormattedToMilliseconds(Number(localStorage.stopwatchRunningTime)));
}
else{
    localStorage.stopwatchRunningTime = 0;
}

// 页面初始化
function pageInit() {
	// 初始化按钮
	if(stopwatchClock.hasClass('inactive')){
	    $("#control").text("开始");
	    $("#record").text("重置");
	} else {
		$("#control").text("暂停");
		$("#record").text("计次");
	}
	
	if(localStorage.records && localStorage.recCount && localStorage.recCount>0) {
		$("tbody").append(localStorage.records);
		for(var i=1; i<=localStorage.recCount; i++) {
			$("#rec_"+i).live("click", function(){ 
				$(this).autocomplete({
					source: singleIds
				})
			});
			$("#rec_"+i).click(function() {
				$(this).select();
			});
		}
	} else {
		localStorage.records = "";
    	localStorage.recCount = 0;
	}
	count =  Number(localStorage.recCount);
}
pageInit();

// 启动暂停
$('#control').on('click',function(){
    if(stopwatchClock.hasClass('inactive')){
    	//启动
    	startStopwatch();
        $("#control").text("暂停");
        $("#record").text("计次");
    } else {
    	//暂停
    	pauseStopwatch(); 
    	$("#control").text("开始");
        $("#record").text("重置");
    }
});

// 计次复位
$('#record').on('click',function(){
	if(stopwatchClock.hasClass('inactive')){
		//重置
		resetStopwatch(); 
		$("#control").text("开始");
        $("#record").text("重置");
    } else {
    	//计次操作
    	isnertRow(); //计次
    }
});

//保存活动
$('#save').on('click',function(){
	var submit = true;
	layer.prompt({
	    title: '请输入本次计时活动标题'
	}, function(title){
		var loader = layer.load(1);
		if(!title || ""==title.trim()) {
			layer.msg("活动名称不能为空");
			layer.close(loader);
			return;
		}
		var parmObj = {
				title : title,
				type : 1,
				recordList : []
		}
		$("tbody tr").each(function(index){
			var cnt = $(this).children().eq(1).children().first().val();
			var rec = $(this).children().eq(2).text();
			if(!cnt || !rec) {
				submit = false;
				return false;
			}
			parmObj.recordList[index] = {
					content : $(this).children().eq(1).children().first().val(),
					recordTime : $(this).children().eq(2).text()
				}
		});
		if(!submit) {
			layer.msg("计次名称不能为空");
			layer.close(loader);
			return;
		}
		if(!parmObj.recordList || parmObj.recordList.length==0) {
			layer.msg("活动至少有一条计次记录");
			layer.close(loader);
			return;
		}
		$.ajax({
		     type: 'POST',
		     url: getRootPath()+"timer/stopwatch/save.do",
		     data: JSON.stringify(parmObj),
		     dataType:"json",  
		     contentType : 'application/json;charset=utf-8', //设置请求头信息  
	    	 success: function(data){
	    		 resetStopwatch();//重置计时
	    		 layer.close(loader);
	    		 layer.msg(data.msg);
	    		 if(data.success) {
	    			 window.location.href = getRootPath()+'center/timer/result.html?tid='+data.tid;
	    		 }
	    	 }
		});
	});
});

// Pressing the clock will pause/unpause the stopwatch.
stopwatchClock.on('click',function(){
    if(stopwatchClock.hasClass('inactive')){
    	//启动
    	startStopwatch()
        $("#control").text("暂停");
        $("#record").text("计次");
    }
    else{
    	//暂停
    	pauseStopwatch();
        $("#control").text("开始");
        $("#record").text("重置");
    }
});

function isnertRow() {
	count++;
	localStorage.recCount = count;
	var tr = "<tr><td>"+count+"</td><td><input id='rec_"+count+"' type='text' maxlength='32' class='span6 m-wrap' data-provide='typeahead' placeholder='请输入计次"+count+"'></td><td>"+stopwatchDigits.text()+"</td></tr>";
	$("tbody").append(tr);
	$("#rec_"+count).autocomplete({
		source: singleIds
	});
	$("#rec_"+count).click(function() {
		$(this).select();
	});
	localStorage.records = $("tbody").html();
}

function startStopwatch(){
    // Prevent multiple intervals going on at the same time.
    clearInterval(stopwatchInterval);

    var startTimestamp = new Date().getTime(),
        runningTime = 0;

    localStorage.stopwatchBeginingTimestamp = startTimestamp;

    // The app remembers for how long the previous session was running.
    if(Number(localStorage.stopwatchRunningTime)){
        runningTime = Number(localStorage.stopwatchRunningTime);
    }
    else{
        localStorage.stopwatchRunningTime = 1;
    }

    // Every 100ms recalculate the running time, the formula is:
    // time = now - when you last started the clock + the previous running time

    stopwatchInterval = setInterval(function () {
        var stopwatchTime = (new Date().getTime() - startTimestamp + runningTime);

        stopwatchDigits.text(returnFormattedToMilliseconds(stopwatchTime));
    }, 10);

    stopwatchClock.removeClass('inactive');
}

function pauseStopwatch(){
    // Stop the interval.
    clearInterval(stopwatchInterval);

    if(Number(localStorage.stopwatchBeginingTimestamp)){

        // On pause recalculate the running time.
        // new running time = previous running time + now - the last time we started the clock.
        var runningTime = Number(localStorage.stopwatchRunningTime) + new Date().getTime() - Number(localStorage.stopwatchBeginingTimestamp);

        localStorage.stopwatchBeginingTimestamp = 0;
        localStorage.stopwatchRunningTime = runningTime;

        stopwatchClock.addClass('inactive');
    }
}

// Reset everything.
function resetStopwatch(){
    clearInterval(stopwatchInterval);

    stopwatchDigits.text(returnFormattedToMilliseconds(0));
    localStorage.stopwatchBeginingTimestamp = 0;
    localStorage.stopwatchRunningTime = 0;
    localStorage.records = "";
	localStorage.recCount = 0;
	count = 0;
	$("tbody").empty();

    stopwatchClock.addClass('inactive');
}


function returnFormattedToMilliseconds(time){
    var milliseconds = Math.floor((time % 1000) / 10),
        seconds = Math.floor((time/1000) % 60),
        minutes = Math.floor((time/(1000*60)) % 60),
        hours = Math.floor((time/(1000*60*60)) % 24);

    milliseconds = milliseconds < 10 ? '0' + milliseconds : milliseconds;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    minutes = minutes < 10 ? '0' + minutes : minutes;

    if(hours <= 0) {
    	return minutes + ":" + seconds + "." + milliseconds;
    } else {
    	return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
    }

}